from fastapi import Request
from app.core.logger import logger
import time

class LoggingMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        start_time = time.time()
        request = Request(scope, receive)
        
        # 记录请求
        logger.info(f"Request: {request.method} {request.url}")
        
        async def send_wrapper(message):
            if message["type"] == "http.response.start":
                process_time = time.time() - start_time
                logger.info(f"Response time: {process_time:.2f}s")
            await send(message)

        await self.app(scope, receive, send_wrapper)